<template>
  <div class="body_all">
    <!-- 操作按钮 -->
    <div class="top_btn">
      <span style="margin-right: 11px"
        ><el-button
          type="primary"
          icon="el-icon-plus"
          @click="edit_admin('', 0)"
          >添加文章</el-button
        ></span
      >
      <span
        ><el-button
          :disabled="!sel_state"
          @click="delsData"
          type="danger"
          icon="el-icon-delete"
          >批量删除</el-button
        ></span
      >
    </div>
    <!-- 表格数据 -->
    <div class="center_content">
      <el-table
        ref="multiTableInst"
        v-loading="loading"
        :data="footerPage.currentPageData"
        @select="handleSelect"
        @select-all="handleSelectAll"
        border
        style="width: 100%"
        :cell-style="tableRowClassName"
        :header-cell-style="{
          background: '#fafafa',
          color: 'rgba(56, 56, 56, 1)',
        }"
      >
        <el-table-column type="selection" width="55" align="center">
        </el-table-column>
        <el-table-column prop="id" label="ID" width="80" align="center">
        </el-table-column>
        <el-table-column prop="title" label="文章标题" align="center">
        </el-table-column>
        <el-table-column label="文章封面" width="300" align="center">
          <template slot-scope="scope">
            <div style="display: flex; justify-content: center; margin: 5px">
              <el-image
                v-if="scope.row.thumb !== null"
                style="height: 100px; border: 1px solid #ebeef5"
                :src="scope.row.thumb"
                :preview-src-list="showImg(scope.row.thumb)"
                fit="contain"
              ></el-image>
            </div>
          </template>
        </el-table-column>
        <el-table-column
          prop="author"
          label="发布者"
          width="100"
          align="center"
        >
        </el-table-column>
        <el-table-column label="是否显示" width="200" align="center">
          <template slot-scope="scope">
            <el-tooltip
              :content="scope.row.show === 1 ? '隐藏' : '显示'"
              placement="top"
            >
              <el-switch
                v-model="scope.row.show"
                @change="showStart(scope.row.show, scope.row.id)"
                active-color="#13ce66"
                inactive-color="#ff4949"
                :active-value="1"
                :inactive-value="2"
              >
              </el-switch>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column label="是否置顶" width="200" align="center">
          <template slot-scope="scope">
            <el-tooltip
              :content="scope.row.top === 1 ? '取消置顶' : '开启置顶'"
              placement="top"
            >
              <el-switch
                v-model="scope.row.top"
                @change="toStart(scope.row.top, scope.row.id)"
                active-color="#13ce66"
                inactive-color="#ff4949"
                :active-value="1"
                :inactive-value="0"
              >
              </el-switch>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column
          prop="addtime"
          label="发布时间"
          width="200"
          align="center"
        >
        </el-table-column>
        <el-table-column prop="address" label="操作" width="150" align="center">
          <template slot-scope="scope">
            <div class="table_btn">
              <button class="edit_btn" @click="edit_admin(scope.row, 2)">
                编辑
              </button>
              <button class="del_btn" @click="del_admin(scope.row.id)">
                删除
              </button>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="sort" label="排序" width="100" align="center">
        </el-table-column>
      </el-table>
    </div>
    <!-- 页码操作 -->
    <div class="footer">
      <el-button v-if="false" @click="firstPage" size="mini">首页</el-button>
      <span :class="footerPage.currentPage === 1 ? 'ban_btn_no' : ''"
        ><el-button
          id="parentpage"
          @click="prevPage"
          size="mini"
          :class="
            footerPage.currentPage === 1 ? 'ban_btn_stop' : 'page_operable'
          "
          >上一页</el-button
        ></span
      >
      <span class="page_operable">{{ footerPage.currentPage }}</span>
      <span>/</span>
      <span>{{ footerPage.totalPage }}</span>
      <span
        :class="
          footerPage.currentPage === footerPage.totalPage ? 'ban_btn_no' : ''
        "
        ><el-button
          id="nextpage"
          @click="nextPage"
          size="mini"
          :class="
            footerPage.currentPage === footerPage.totalPage
              ? 'ban_btn_stop'
              : 'page_operable'
          "
          >下一页</el-button
        ></span
      >
      <el-button v-if="false" @click="lastPage" size="mini">尾页</el-button>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      loading: false,
      editImag: [], // 新增
      sel_state: false, // 选中状态
      selData: [], // 选中数据
      tableData: [
        {
          id: 1,
          title: "首页广告",
          img_src:
            "https://fuss10.elemecdn.com/e/5d/4a731a90594a4af544c0c25941171jpeg.jpeg",
          create_time: "2016-05-02",
          state: 1,
        },
        {
          id: 2,
          title: "应用中心轮播",
          img_src:
            "https://fuss10.elemecdn.com/e/5d/4a731a90594a4af544c0c25941171jpeg.jpeg",
          create_time: "2016-05-02",
          state: 1,
        },
      ],
      footerPage: {
        list: null,
        listLoading: true,
        totalPage: 1, // 统共页数，默认为1
        currentPage: 1, //当前页数 ，默认为1
        pageSize: 5, // 每页显示数量
        currentPageData: [], //当前页显示内容
        headPage: 1,
      },
    };
  },
  created() {
    this.loading = true;
    this.getDate();
  },
  methods: {
    // 获取列表内容
    getDate() {
      this.$cmsapi
        .ArticleList()
        .then((res) => {
          if (res.code === 1 && res.msg === "登录已过期,请重新登录") {
            // 如果身份过期需要退出重新登陆
            var storage = window.localStorage;
            storage.clear();
            setTimeout(() => {
              this.$store.commit("logout", "false");
              this.$router.push({ path: "/login" });
            }, 1000);
            return;
          }
          this.tableData = res.data;
          this.footerPage.totalPage = Math.ceil(
            this.tableData.length / this.footerPage.pageSize
          );
          this.footerPage.totalPage =
            this.footerPage.totalPage == 0 ? 1 : this.footerPage.totalPage;
          this.getCurrentPageData();
        })
        .catch((error) => {
          console.log(error);
        });
    },
    // 表格全选状态
    handleSelectAll() {
      if (this.getIsAllChecked()) {
        //全选逻辑
        this.selData = this.footerPage.currentPageData;
        this.sel_state = true;
      } else {
        //取消逻辑
        this.selData = this.$options.data().selData;
        this.sel_state = false;
      }
    },
    getIsAllChecked() {
      //下面这行为获取table组件中的全选checkbox的勾选状态
      return this.$refs.multiTableInst.store.states.isAllSelected;
    },
    // 监听表格单选数据
    handleSelect(rows, row) {
      if (rows.length > 0) {
        this.sel_state = true;
      } else {
        this.sel_state = false;
      }
      this.selData = rows;
    },
    // 设置当前页面的数据
    getCurrentPageData() {
      let begin = (this.footerPage.currentPage - 1) * this.footerPage.pageSize;
      let end = this.footerPage.currentPage * this.footerPage.pageSize;
      this.footerPage.currentPageData = this.tableData.slice(begin, end);
      this.loading = false;
    },
    // 根据列表有无图片进行列表内边距调整
    tableRowClassName({ row, rowIndex }) {
      if (row.thumb !== null) {
        return "padding:0px";
      }
    }, //上一页
    prevPage() {
      if (this.footerPage.currentPage == 1) {
        return false;
      } else {
        this.loading = true;
        this.footerPage.currentPage--;
        this.getCurrentPageData();
      }
      document.getElementById("parentpage").blur();
    }, // 下一页
    nextPage() {
      if (this.footerPage.currentPage == this.footerPage.totalPage) {
        return false;
      } else {
        this.loading = true;
        this.footerPage.currentPage++;
        this.getCurrentPageData();
      }
      document.getElementById("nextpage").blur();
    }, //尾页
    lastPage() {
      if (this.footerPage.currentPage == this.footerPage.totalPage) {
        return false;
      } else {
        this.loading = true;
        this.footerPage.currentPage = this.footerPage.totalPage;
        this.getCurrentPageData();
      }
    }, //首页
    firstPage() {
      this.loading = true;
      this.footerPage.currentPage = this.footerPage.headPage;
      this.getCurrentPageData();
    },
    // 大图预览
    showImg(img) {
      let imgArr = [];
      imgArr.push(img);
      return imgArr;
    },
    showStart(callback, id) {
      this.$cmsapi
        .ArticleShowState(id)
        .then((res) => {
          // console.log(res);
        })
        .catch((error) => {
          console.log(error);
        });
    },
    // 状态修改
    toStart(callback, id) {
      this.$cmsapi
        .ArticleToState(id)
        .then((res) => {
          // console.log(res);
        })
        .catch((error) => {
          console.log(error);
        });
    },
    // 编辑
    edit_admin(obj, i) {
      let params = "";
      if (i === 1) {
        params = {
          pid: obj.id,
          pidName: obj.name,
        };
      } else {
        params = obj;
      }
      this.$router.push({
        path: "add",
        query: params,
      });
    },
    // 批量删除
    delsData() {
      let delsId = "";
      this.selData.forEach((item, index) => {
        if (index === 0) {
          delsId = item.id;
        } else {
          delsId = delsId + "," + item.id;
        }
      });
      this.del_admin(delsId);
    },
    // 删除
    del_admin(id) {
      let that = this;
      this.$confirm("此操作将永久删除该栏目, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.loading = true;
          this.$cmsapi
            .ArticleDelete(id)
            .then((res) => {
              let mestext = "删除成功！";
              let type = "success";
              if (res.code === 1) {
                type = "error";
                mestext = res.msg;
              }
              this.$message({
                type: type,
                message: mestext,
              });
              that.getDate();
            })
            .catch((error) => {
              console.log(error);
            });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
  },
};
</script>